<template>
  <div class="container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">报表查询</span>
          <el-button type="primary" @click="handleExportAll">导出Excel</el-button>
        </div>
      </template>

      <div class="toolbar">
        <div class="search-bar">
          <el-input
            v-model="searchInput"
            placeholder="请输入编码/单号/类型/描述搜索"
            class="search-input"
            :suffix-icon="Search"
            @keyup.enter="handleSearch"
          />
        </div>

        <div class="type-select">
          <el-select v-model="storageType" placeholder="请选择类型" clearable>
            <el-option label="入库" value="I" />
            <el-option label="出库" value="O" />
          </el-select>
        </div>

        <div class="date-picker">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
          />
        </div>

        <div class="buttons">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>

      <el-table 
        :data="tableData" 
        style="width: 100%" 
        border 
        stripe
        :height="tableHeight"
      >
        <el-table-column prop="storageNumber" label="单号" width="180" />
        <el-table-column prop="code" label="编码" width="120" />
        <el-table-column prop="type" label="类型" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="storageType" label="操作类型" width="100">
          <template #default="scope">
            {{ scope.row.storageType === 'I' ? '入库' : '出库' }}
          </template>
        </el-table-column>
        <el-table-column prop="accumulation" label="结存" width="100" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="createTime" label="操作时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.createTime).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            }).replace(/\//g, '-') }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElNotification } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getStorageList } from '@/axios/api/package-material/storage'
import * as XLSX from 'xlsx'
//@ts-ignore
import { throttle } from 'lodash'

interface StorageRecord {
  storageNumber: string | null
  code: string
  type: string
  description: string
  unit: string
  quantity: number
  storageType: string
  remark: string
  operator: string
  createTime: string
}

// 状态定义
const searchInput = ref('')
const storageType = ref('')
const dateRange = ref<[Date, Date] | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableHeight = ref(window.innerHeight - 64 - 40 - 51 - 52 - 72 - 20 - 64)
const tableData = ref<StorageRecord[]>([])

// 方法定义
const updateTableHeight = () => {
  tableHeight.value = window.innerHeight - 64 - 40 - 51 - 52 - 72 - 20 - 64
}

const fetchData = async () => {
  try {
    const params: any = {
      search: searchInput.value,
      storage_type: storageType.value,
      page: currentPage.value,
      page_size: pageSize.value
    }
    if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
      params.start_date = dateRange.value[0]
      params.end_date = dateRange.value[1]
    }
    const response = await getStorageList(params)
    
    // 直接使用返回的分页数据
    tableData.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    console.error('Error fetching data:', error)
    ElNotification({
      title: '错误',
      message: '获取数据失败',
      type: 'error',
    })
  }
}

const handleSearch = throttle(() => {
  currentPage.value = 1
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

const resetSearch = throttle(() => {
  searchInput.value = ''
  storageType.value = ''
  dateRange.value = null
  currentPage.value = 1
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

const handleCurrentChange = throttle((val: number) => {
  currentPage.value = val
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

const handleSizeChange = throttle((val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchData()
}, 1000, {
  leading: true,
  trailing: false
})

// 导出excel
const exportExcel = async (tableData: StorageRecord[]) => {
    if (tableData.length == 0) {
        ElNotification({
            title: 'Error',
            message: '没有数据',
            type: 'error',
        })
        return;
    }

    const ws = XLSX.utils.json_to_sheet(tableData)
    const wb = { Sheets: { 'Data': ws }, SheetNames: ['Data'] }
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })

    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' })
    const url = URL.createObjectURL(data)

    const link = document.createElement('a')
    link.href = url
    link.style.display = 'none'
    link.download = 'storage-report.xlsx'
    document.body.appendChild(link)

    link.click()
    
    setTimeout(() => {
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
    }, 100)
}

// 获取所有数据并导出
const handleExportAll = async () => {
    try {
        const params: any = {
            search: searchInput.value,
            storage_type: storageType.value,
            page: 1,
            page_size: total.value // 使用总数作为页面大小，这样一次就能获取所有数据
        }
        if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
            params.start_date = dateRange.value[0]
            params.end_date = dateRange.value[1]
        }
        const response = await getStorageList(params)
        if (response.records) {
            exportExcel(response.records)
        }
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '导出数据失败',
            type: 'error',
        })
    }
}

// 生命周期钩子
onMounted(() => {
  fetchData()
  window.addEventListener('resize', updateTableHeight)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})
</script>

<style scoped>
.container {
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.type-select {
  width: 120px;
}

:deep(.type-select .el-select) {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
  background-color: var(--el-color-primary-light-9);
}

.buttons {
  display: flex;
  gap: 10px;
}
</style> 